package javachongkao.面向对象下.接口Comparator;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

//7-1 jmu-Java-04面向对象进阶--02-接口-Comparator
//Arrays.sort可以对所有实现Comparable的对象进行排序。但如果有多种排序需求，如有时候需对name进行降序排序，有时候只需要对年龄进行排序。使用Comparable无法满足这样的需求。可以编写不同的Comparator来满足多样的排序需求。
//
//1.编写PersonSortable2类
//属性：private name(String)、private age(int)
//有参构造函数：参数为name,age
//toString方法：返回格式name-age
//
//2 编写Comparator类
//编写NameComparator类，实现对name进行升序排序
//编写AgeComparator类，对age进行升序排序
//3.main方法中
//输入n
//输入n行name age，并创建n个对象放入数组
//对数组按照name进行升序排序后输出。
//在3的基础上对数组按照age进行升序排序后输出。
//最后最后两行使用如下代码输出NameComparator与AgeComparator所实现的所有接口。
//System.out.println(Arrays.toString(NameComparator.class.getInterfaces()));
//System.out.println(Arrays.toString(AgeComparator.class.getInterfaces()));
class PersonSortable2 {
    private String name;
    private int age;

    public PersonSortable2(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return name + "-" + age;
    }
}

class NameComparator implements Comparator<PersonSortable2> {
    @Override
    public int compare(PersonSortable2 p1, PersonSortable2 p2) {
        return p1.getName().compareTo(p2.getName());
    }
}

class AgeComparator implements Comparator<PersonSortable2> {
    @Override
    public int compare(PersonSortable2 p1, PersonSortable2 p2) {
        return Integer.compare(p1.getAge(), p2.getAge());
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        PersonSortable2[] people = new PersonSortable2[n];

        for (int i = 0; i < n; i++) {
            String name = scanner.next();
            int age = scanner.nextInt();
            people[i] = new PersonSortable2(name, age);
        }

        // 按name升序排序
        Arrays.sort(people, new NameComparator());
        System.out.println("NameComparator:sort");
        for (PersonSortable2 person : people) {
            System.out.println(person);
        }

        // 按age升序排序
        Arrays.sort(people, new AgeComparator());
        System.out.println("AgeComparator:sort");
        for (PersonSortable2 person : people) {
            System.out.println(person);
        }

        // 输出Comparator实现的接口
        System.out.println(Arrays.toString(NameComparator.class.getInterfaces()));
        System.out.println(Arrays.toString(AgeComparator.class.getInterfaces()));

        scanner.close();
    }
}
